<template>
  <div class="post-container">
    <h1>用户发帖管理</h1>
    <div class="post-header">
      <!-- 修改批量删除按钮，绑定点击事件 -->
      <el-button
        type="danger"
        size="normal"
        icon="el-icon-delete-solid"
        @click="handleBatchDelete">
        批量删除
      </el-button>
      <el-input
        placeholder="请输入发帖标题"
        v-model="postTitle" size="20">
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
      <el-select v-model="postType" clearable placeholder="请选择发帖分类">
        <el-option
          v-for="item in typeOptions"
          :key="item.enum_id"
          :label="item.enum_value"
          :value="item.enum_key">
        </el-option>
      </el-select>
      <el-button type="primary" size="normal" icon="el-icon-search" @click="handleSearch">
        搜索
      </el-button>
      <el-button size="normal" icon="el-icon-refresh" @click="handleClear">
        重置
      </el-button>

      <!-- 修改新增按钮，绑定点击事件 -->
      <el-button
        type="success"
        size="normal"
        icon="el-icon-circle-plus"
        @click="handleAdd">
        新增
      </el-button>
      <!--      <button class="myButton"><i class="el-icon-circle-plus" style="margin-right: 5px"></i>新增</button>-->
    </div>
    <div v-if="!tableData || tableData.length < 1" class="juzhong">
      <span><i class="el-icon-loading"></i>
      加载中</span>
      <el-divider></el-divider>
    </div>
    <div v-else class="post-table">
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          width="55"
          align="center"
          header-align="center">
        </el-table-column>
        <el-table-column
          prop="post_id"
          label="帖子id"
          :width="100"
          align="center"
          header-align="center">
        </el-table-column>
        <el-table-column
          prop="nickname"
          label="用户昵称"
          align="center"
          header-align="center">
        </el-table-column>
        <el-table-column
          prop="post_title"
          label="发帖标题"
          align="center"
          header-align="center">
        </el-table-column>
        <el-table-column
          align="center"
          header-align="center"
          prop="is_top"
          label="是否置顶"
          :width="100">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.is_top"
                       active-color="#13ce66"
                       inactive-color="#FFE5CC"
                       @change="(val) => handleSwitchChange(val, scope.row)">>
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          header-align="center"
          prop="status"
          label="状态"
          :width="100">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.status ? 'success' : 'danger'"
              disable-transitions>{{ scope.row.status ? '正常' : '违规' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          header-align="center"
          label="日期"
          prop="update_time"
        >
          <!--          <template slot-scope="scope">{{ scope.row.update_time }}</template>-->
        </el-table-column>

        <!-- 在操作列添加删除按钮 -->
        <el-table-column label="操作" align="center" width="300">
          <template slot-scope="scope">
            <div style="display: flex">
              <el-button @click="getPostDetail(scope.row.post_id)">查看详情</el-button>
              <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="post-bottom">
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>

    <!--        发布话题弹框-->
    <el-dialog
      width="80vw" title="新增发帖" :visible.sync="adddialogVisible" append-to-body
    >
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="topicForm"
        status-icon
        label-width="auto"
        :rules="rules"
      >
        <el-form-item label="话题名称：" prop="post_title">
          <el-input
            v-model="topicForm.post_title"
            style="width: 600px;height:40px;"
            maxlength="30"
            placeholder=""
            show-word-limit
            type="text"
          />

        </el-form-item>
        <el-form-item label="内容：" prop="post_content">
          <WangEditor ref="editor" v-model="topicForm.post_content" style="width: 60vw;height: 60vh"/>
        </el-form-item>
        <el-form-item label="话题类型：" prop="post_type">
          <el-select
            v-model="topicForm.post_type"
            placeholder="请选择话题类型"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.enum_id"
              :label="item.enum_value"
              :value="item.enum_key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="技术标签：" prop="direction_id">
          <el-select
            v-model="topicForm.direction_id"
            placeholder="请选择技术标签"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in Techoptions"
              :key="item.direction_id"
              :label="item.direction_title"
              :value="item.direction_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleFormRef')">
            提交
          </el-button>
          <el-button @click="handleCancel('ruleFormRef')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {Message} from 'element-ui'
import {getPagePost, auditPost, topPost, addPost, deletePost} from "@/api/comment";
import {getDictEnum, getAuditLog, getDirections} from "@/api/commen";
import WangEditor from '@/components/WangEditor';

export default {

  name: 'UserPost',
  components: {
    WangEditor
  },
  data() {
    return {
      tableData: null,
      pageNum: 1,     // 当前页码
      pageSize: 10,   // 每页条数
      total: 0,      //总共数据量
      postType: null,
      postTitle: null,
      typeList: [{}],  //帖子分类
      typeOptions: [{}],
      isAudit: false,
      adminLog: {status: null},
      ispass: 1,
      currentPostId: null,
      multipleSelection: [], // 存储选中的行
      adddialogVisible: false, // 控制新增弹窗显示
      topicForm: {
        post_content: '',
        post_title: '',
        post_type: '',
        direction_id: '',
        publisher_id: '',
        course_id: ''
      },
      Techoptions: [{}],
      rules: {
        name: [
          {required: true, message: '请输入话题名称', trigger: 'blur'},
          {min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur'}
        ],
        content: [
          {required: true, message: '请输入内容', trigger: 'blur'}
        ],
        topicType: [
          {required: true, message: '请选择话题类型', trigger: 'change'}
        ]
      }
    }
  },
  methods: {
    async handleSwitchChange(val, post) {
      try {
        // 确认弹窗
        const action = val ? '置顶' : '取消置顶'
        await this.$confirm(`确定要${action}该内容吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        // 调用API
        try {
          console.log("置顶", val)
          post.is_top = val
          console.log(post)
          await this.updateTop(post)
        } catch (e) {
          this.$message.error("操作失败！")
          return
        }
        this.$message.success(`${action}成功`)
      } catch (error) {
        // 用户点击取消或API调用失败
        if (error !== 'cancel') {
          this.$message.error(error.message || '操作失败')
        }
        // 回滚switch状态
        this.$nextTick(() => {
          post.is_top = !val
        })
      }
    },
    handleSearch() {
      this.ClearPage();
      this.getPost();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    async getPost() {
      const data = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        post_type: this.postType,
        post_title: this.postTitle,
      }
      console.log("获取发帖列表请求列表data", data)
      const rep = await getPagePost(data);
      this.tableData = rep.items;
      this.total = rep.total;
    },
    ClearPage() {
      this.pageNum = 1;
    },
    handleClear() {
      this.ClearPage();
      this.postType = null;
      this.postTitle = null;
      this.getPost();
    },
    async getType() {
      this.typeOptions = await getDictEnum('互动问答');
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getPost();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getPost();
    },
    getPostDetail(postId) {
      this.$router.push(`/post/${postId}`)
    },
    // 打开新增弹窗
    handleAdd() {
      this.adddialogVisible = true;
      this.resetForm();
    },
    async fetchDirections() {
      try {
        const rep = await getDirections();
        this.Techoptions = rep
        console.log(rep)
      } catch (err) {
        console.log(err);
        this.$message.error("获取方向失败")
      }
    },
    // 提交新增表单
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.topicForm.post_content = this.$refs.editor.getContent()
          this.topicForm.publisher_id = this.$store.getters.userId
          this.topicForm.course_id = 1
          try {
            // 这里调用新增帖子的API
            await addPost(this.topicForm);
          } catch (error) {
            Message.error('新增帖子失败');
            console.error(error);
            return;
          }
          Message.success('新增帖子成功');
          this.adddialogVisible = false;
          await this.getPost(); // 刷新列表
        } else {
          return false;
        }
      });
    },

    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
      this.topicForm = {
        name: '',
        content: '',
        topicType: '',
        technology: ''
      };
    },
    handleCancel(formName) {
      this.resetForm(formName);
      this.adddialogVisible = false;
    },
    // 批量删除
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        Message.warning('请至少选择一条记录');
        return;
      }

      this.$confirm('确定要删除选中的帖子吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const ids = this.multipleSelection.map(item => item.post_id);
          // 调用批量删除API
          await deletePost(ids);
          Message.success('删除成功');
          await this.getPost(); // 刷新列表
        } catch (error) {
          Message.error('删除失败');
          console.error(error);
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    // 单个删除
    handleDelete(row) {
      this.$confirm('确定要删除该帖子吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 调用单个删除API
          await deletePost(row.post_id);
        } catch (error) {
          Message.error('删除失败');
          console.error(error);
          return
        }
        Message.success('删除成功');
        await this.getPost(); // 刷新列表
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    async updateTop(post) {
      console.log(post);
      const data = {
        post_id: post.post_id,
        is_top: post.is_top,
      }
      await topPost(data);
    }
  },
  mounted() {
    this.getPost();
    this.getType();
    this.fetchDirections();
  }
}

</script>

<style lang="scss" scoped>
/* 确保 Quill 容器和工具栏同宽 */
.ql-container {
  width: 1000px !important;
}

.ql-snow {
  width: 1000px !important;
}

.myButton {
  cursor: pointer;
  color: #fff;
  padding: 13px;
  border-radius: 10px;
  border: none;
  background-color: #20E2D7;

  &:hover {
    opacity: 0.5;
  }
}

.post-container {
  margin: auto auto;
  width: 80vw;
}

.post-header {
  display: flex;
  justify-content: start;
  margin: auto;
  width: 100%;
  padding: 10px 0;
}

.post-bottom {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
<style scoped>
.el-input {
  margin-right: 1em;
  width: 30em;

}

.el-button {
  margin: 0 10px;
}
</style>
